package com.three.service;

import com.three.api.protocol.Packet;
import com.three.api.push.PushSender;
import com.three.common.message.base.ErrorMessage;
import com.three.common.message.mail.ReadMailReqMessage;
import com.three.common.message.mail.ReadMailRespMessage;
import com.three.config.LanguageConfig;
import com.three.constant.LanguageId;
import com.three.domain.mail.MailPo;
import com.three.domain.mail.MailType;
import com.three.exception.GameException;
import com.three.protocol.CommandEnum;
import com.three.protocol.MailModule;
import com.three.repository.MailRepository;
import com.three.reward.RewardItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by Mathua on 2017/6/23.
 */
@Service
public class MailModuleService {

    private static final Logger LOGGER = LoggerFactory.getLogger(MailModuleService.class);

    @Autowired
    private MailRepository mailRepository;

    /**
     * 发送邮件
     * @param receiverId 接收者id
     * @param subject 主题
     * @param content 内容
     * @param items 奖励
     * @param isRecommend 是否为推荐
     * @param sendTime 发送时间
     * @param deleteTime 删除时间
     * @throws GameException
     */
    public void sendMail(long receiverId, String subject, String content, List<RewardItem> items, boolean isRecommend, Date sendTime, Date deleteTime) throws GameException {
        MailPo mailPo = MailPo.build(receiverId, subject, content, items, isRecommend, sendTime, deleteTime);
        mailRepository.save(mailPo);

        MailModule.NotifyMailList_200.Builder builder = MailModule.NotifyMailList_200.newBuilder();
        toMailData(builder, mailPo);
        Packet packet = Packet.build(CommandEnum.Command.NOTIFY_MAIL_LIST, builder.build().toByteArray());

        PushSender sender = PushSender.get();
        sender.send(packet, mailPo.getReceiverId());
    }

    /**
     * 构造protobuf数据
     * @param builder protobuf对象
     * @param mailPo 邮件对象
     */
    public void toMailData(MailModule.NotifyMailList_200.Builder builder, MailPo mailPo) {
        // 判断是否发送邮件
        if(!mailPo.getSendTime().after(new Date())) {

            MailModule.Mail.Builder mail = MailModule.Mail.newBuilder();
            mail.setMailId(mailPo.getEntityId());
            mail.setMailType(mailPo.getMailType().getId());
            mail.setSubject(mailPo.getSubject());
            mail.setContent(mailPo.getContent());
            if(mailPo.getItemsJson() != null) {
                mail.setItemsJson(mailPo.getItemsJson());
            }
            mail.setIsRecommend(mailPo.isRecommend());
            mail.setSendTime(mailPo.getSendTime().getTime());
            mail.setHadRead(mailPo.isHadRead());
            builder.addMails(mail);

            // 更新发送状态
            mailPo.setHadSend();
        }
    }

    /**
     * 阅读邮件
     * @param message
     */
    public void readMail(ReadMailReqMessage message) {
        MailPo mailPo = mailRepository.getOne(message.getMailId());
        if(mailPo == null) {
            LOGGER.error("mail not exist.mail id={}", message.getMailId());
            ErrorMessage.from(message).setReason(LanguageConfig.getText(LanguageId.MAIL_NOT_EXIST)).send();
            return;
        }
        try {
            mailPo.read();
            ReadMailRespMessage.from(message).setMailId(message.getMailId()).send();
            // 删除邮件
            if(mailPo.getMailType() == MailType.ITEMS_MAIL) {
                LOGGER.info("delete mail.mail info={}", mailPo);
                mailRepository.delete(message.getMailId());
            }
        } catch (GameException e) {
            LOGGER.error(e.getErrorMsg());
            ErrorMessage.from(message).setReason(e.getErrorMsg()).send();
        }
    }
}
